package com.gamemost.templestay;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;

import com.gamemost.dao.ResourceData;
import com.gamemost.layout.LayoutViewReadBook;
import com.gamemost.managers.ResourcesManager;

public class Config {
	public static boolean isTest = false;
	public static boolean copyRes = true;

	public static int NOT_SET = 0;
	public static int FIX_LAYOUT = 2;
	public static int REFLOW_LAYOUT = 1;
	
	public static String ROOT = "/templestay";
	public static String FONT = ROOT+"/Font";
	public static String EPUB_FILE = ROOT + "/Epub";
	public static String DATA_APP = ROOT + "/Data";
	public static String CACHE = ROOT + "/Cache";
	public static String CACHE1 = CACHE + "/Cache1";
	public static String CACHE2 = CACHE + "/Cache2";
	public static String CACHE3 = CACHE + "/Cache3";
	public static String IMAGE_BOOK = DATA_APP + "/ImageBook";
	public static String IMAGE_STAND = DATA_APP + "/ImageStand";
	public static String IMAGE_STAND_INLIST = DATA_APP + "/ImageStandInList";
	public static String IMAGE_BOOKMARK = DATA_APP + "/ImageBookmark";
	public static String JS = ROOT + "/js";
	public static String CSS = ROOT + "/css";
	public static String IMG = ROOT + "/image";

	
	public static String FONT_SIZE = "font_size";
	public static String[] cache = { "", "", "" };
	public static String[] CACHE_PATH = {CACHE1,CACHE2,CACHE3};
	public static int cacheAvailable = 0;
	public static boolean fullCache = false;
	public static String del;
	public static boolean isCache = false;
	public static String pathEnv = Environment.getExternalStorageDirectory()
			.getPath();
	static String[] fonts;
	public static boolean colorChange = false; // to know color change, to set color reflow.
	public static String font;
	public static String fontSize;
	public static String color;
	public static int codeColor;
	public static String uriFont;
	public static int lang = 1;
	public static void initFolder() {
		fonts = ResourcesManager.ac.getResources().getStringArray(R.array.list_font_values);
		for (int i = 0;i < fonts.length;i++) {
			copyFile(ResourcesManager.ac.getBaseContext(), fonts[i]+".ttf");
		}
		getCacheFromPref();
		if (ResourcesManager.ac.getResources().getColor(R.color.yellowMilk) == codeColor) {
			Config.color = "#f8f2da";
		} else if (ResourcesManager.ac.getResources().getColor(R.color.black) == codeColor) {
			Config.color = "#000000";
		} else {
			Config.color = "#ffffff";
		}
		LayoutViewReadBook.creatFolder(ROOT);
		LayoutViewReadBook.creatFolder(FONT);
		LayoutViewReadBook.creatFolder(EPUB_FILE);
		LayoutViewReadBook.creatFolder(DATA_APP);
		LayoutViewReadBook.creatFolder(CACHE);
		LayoutViewReadBook.creatFolder(CACHE1);
		LayoutViewReadBook.creatFolder(CACHE2);
		LayoutViewReadBook.creatFolder(CACHE3);
		LayoutViewReadBook.creatFolder(IMAGE_BOOK);
		LayoutViewReadBook.creatFolder(IMAGE_STAND);
		LayoutViewReadBook.creatFolder(IMAGE_STAND_INLIST);
		LayoutViewReadBook.creatFolder(IMAGE_BOOKMARK);
		LayoutViewReadBook.creatFolder(JS);
		LayoutViewReadBook.creatFolder(CSS);

		
		uriFont = Uri.fromFile(new File(pathEnv+FONT)).toString();
	
	}
	
	public static void saveCacheToPref() {
		System.out.println("saveToCache");
		Editor editor = PreferenceManager.getDefaultSharedPreferences(
				ResourcesManager.ac.getBaseContext()).edit();
		editor.putString("CACHE1", cache[0]);
		editor.putString("CACHE2", cache[1]);
		editor.putString("CACHE3", cache[2]);
		editor.putInt("CACHE_AVAI", cacheAvailable);
		editor.putString("FONT", font);
		editor.putInt("LANG", lang);
		editor.putInt("COLOR", codeColor);
		editor.putString(FONT_SIZE, fontSize);
		editor.commit();
	}

	public static void getCacheFromPref() {
		SharedPreferences pref = PreferenceManager
				.getDefaultSharedPreferences(ResourcesManager.ac
						.getBaseContext());
		cache[0] = pref.getString("CACHE1", "");
		cache[1] = pref.getString("CACHE2", "");
		cache[2] = pref.getString("CACHE3", "");
		System.out.println("getCacheFromPref "+cache[0]+","+cache[1]+","+cache[2]);

		cacheAvailable = pref.getInt("CACHE_AVAI", 0);
		font = pref.getString("FONT", fonts[3]);
		fontSize = pref.getString(FONT_SIZE, ResourcesManager.ac.getResources().getString(R.string.MEIDUM));
		lang = pref.getInt("LANG", 1);
		codeColor = pref.getInt("COLOR", ResourcesManager.ac.getResources().getColor(R.color.white));
	}
	public static void unregisToCache(String idbook) {
		System.out.println("unregisterToCache start");
		for (int i = 0;i <cache.length;i++) {
			if (cache[i].equals(idbook)) {
				cache[i] = "";
				if (i == 0) {
					del = CACHE1;
				} else if (i == 1) {
					del = CACHE2;
				} else if (i == 2) {
					del = CACHE3;
				}
				Runnable thread = new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						System.out.println("delete start");
						File dir = new File(Environment
								.getExternalStorageDirectory().getPath() + del);
						if (deleteDir(dir)) {
							LayoutViewReadBook.creatFolder(del);
						}					
					}
				};
				thread.run();
			}
		}
	}
	public static String getCache(String book) {
		System.out.println("getCache start "+book);
		String cachePath = CACHE1;
		isCache = false;
		for (int i = 0; i < cache.length; i++) {
			System.out.println("getCache val "+i+": "+cache[i]);
			if (!"".equals(book) && cache[i].equals(book)) {
				if (i == 0) {
					cachePath = CACHE1;
				} else if (i == 1) {
					cachePath = CACHE2;
				} else if (i == 2) {
					cachePath = CACHE3;
				}				
				System.out.println("id book avai " + i);
				isCache = true;
				return cachePath;
			}

		}
		if (cacheAvailable == 0) {
			cachePath = CACHE1;
		} else if (cacheAvailable == 1) {
			cachePath = CACHE2;
		} else if (cacheAvailable == 2) {
			cachePath = CACHE3;
		}
		System.out.println("getCache available "+cacheAvailable);
		cache[cacheAvailable++] = book;
		if (cacheAvailable == 3) {
			cacheAvailable = 0;
			fullCache = true;
		}
		System.out.println("getCache fullCache "+fullCache);
		if (fullCache) {
			if (cacheAvailable == 0) {
				del = CACHE1;
			} else if (cacheAvailable == 1) {
				del = CACHE2;
			} else if (cacheAvailable == 2) {
				del = CACHE3;
			}
			System.out.println("del cache " + del + "cacheAvai "+cacheAvailable);
			cache[cacheAvailable] = "";
			Runnable thread = new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					System.out.println("delete start");
					File dir = new File(Environment
							.getExternalStorageDirectory().getPath() + del);
					final File to = new File(Environment
							.getExternalStorageDirectory().getPath() + CACHE + "/del");
					dir.renameTo(to);
					if (deleteDir(to)) {
						System.out.println(to.getPath()+" del success "+dir.getPath());
						LayoutViewReadBook.creatFolder(del);
						System.out.println("create folder "+del);
					}					
				}
			};
			thread.run();
		}
		System.out.println("getCache return "+cachePath);
		return cachePath;
	}
	Runnable thread;
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}

	public static boolean copyFile(Context context, String fileName) {
		boolean status = false;
		File f = new File(pathEnv + FONT + "/" + fileName);
		if (!f.exists()) {
			try {
				FileOutputStream out = new FileOutputStream(f);
				InputStream in = context.getAssets().open("Font/"+fileName);
				// Transfer bytes from the input file to the output file
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				// Close the streams
				out.close();
				in.close();
				status = true;
			} catch (Exception e) {
				status = false;
			}
		} else status = false;
		return status;
	}	
}
